﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using App.Core.Extensions;
using App.Data;
using App.Core.Mail;

public partial class Pages_Admin_NewsletterTest : BasePage
{
    private int _NewsletterID = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        BindPageInfo();
        if (!IsPostBack)
        {
            lblSubject.Text = WebUtil.GetQueryStringInString("Subject");
            BindNewsletterInfo();
        }
    }
    protected void BindPageInfo()
    {
        _NewsletterID = WebUtil.GetQueryStringInInt(AppConstants.QueryString.ID);
        Page.Title = WebUtil.GetPageTitle("Test Newsletter");
    }
    protected void BindNewsletterInfo()
    {
        BtcHousingEntities context = new BtcHousingEntities();
        var newsLetter = context.NewsLetters.FirstOrDefault(P => P.ID == _NewsletterID);
        if (newsLetter == null)
            ShowNotFoundMessage();
        else
        {
            divNewsletterHtml.InnerHtml = newsLetter.Html;
        }
    }
    protected void ShowNotFoundMessage()
    {
        WebUtil.ShowMessageBox(divMessage, "Newsletter not found.", true);
        pnlFormContainer.Visible = false;
    }
    protected void TestNewsletter()
    {
        BtcHousingEntities context = new BtcHousingEntities();
        var newsLetter = context.NewsLetters.FirstOrDefault(P => P.ID == _NewsletterID);
        if (newsLetter == null)
            WebUtil.ShowMessageBox(divMessage, "Newsletter not found.", true);
        else
        {
            String fromEmail = ConfigReader.SupportEmail;
            String toEmail = txtEmail.Text;
            try
            {
                MailManager.SendMail(toEmail, String.Empty, String.Empty, fromEmail, lblSubject.Text.HtmlEncode(), newsLetter.Html);
                WebUtil.ShowMessageBox(divMessage, "Successfully sent the Newsletter", false);
            }
            catch(Exception ex)
            {
                WebUtil.ShowMessageBox(divMessage, String.Format("Unable to Send email. Review following error Message: <br/>{0}", ex.Message), true);
            }
        }
    }
    protected void btnSend_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            TestNewsletter();
        }
    }
}